import React, { useState, useEffect, useRef } from "react";
import Common from "@/components/common/index"
import { Button, Form, Input, Table, Pagination, Popconfirm, Select, Tag, Typography, message } from 'antd';
import { SearchOutlined, ReloadOutlined, PlusOutlined } from '@ant-design/icons';
import type { TableColumnsType, PaginationProps } from 'antd';
import { roleList, getUsers, resetPassword, getUserById, deleteUser, addUser, editUser } from "@/common/api"
import AddCount from "./addCount";





const Account: React.FC = () => {
    useEffect(() => {
        getRoles()
        getData()
    }, []);
    const [form] = Form.useForm();
    const [loadings, setLoadings] = useState<boolean>(false);
    const [roleData, setRoleData] = useState<any[]>([]);
    const [tableData, setTableData] = useState<any[]>([]);
    const getRoles = () => {
        roleList().then((res: any) => {
            if (res.success) {
                let data = []
                for (let i in res.data) {
                    data.push({
                        label: res.data[i],
                        value: i
                    })
                }
                setRoleData(data)
            }
        })
    }
    const getData = () => {
        const values = form.getFieldsValue();
        values['needYearMonth'] = values['needYearMonth'] ? values['needYearMonth'].format('YYYYMM') : ''
        let param = {
            ...values,
            pageSize: pageSizeRef.current,
            pageNum: pageNumRef.current
        }
        setLoadings(true)
        getUsers(param).then((res: any) => {
            setLoadings(false)
            if (res.success) {
                setTableData(res.data.records)
                total.current = res.data.total
            } else {

            }
        })
    }

    const onFinish = () => {
        pageNumRef.current = 1;
        setCurrent(1)
        getData()
    }


    const getTop = () => {
        return <Form
            layout="inline"
            form={form}
            onFinish={onFinish}
            autoComplete="off"
        >
            <Form.Item name="userName" label="用户名 :" style={{ marginBottom: '10px' }}>
                <Input placeholder="请输入用户名" />
            </Form.Item>
            <Form.Item name="department" label="部门:">
                <Input placeholder="请输入部门" />
            </Form.Item>
            <Form.Item name="userRole" label="角色:">
                <Select
                    style={{ width: "150px" }}
                    options={roleData}
                    placeholder="请选择角色"
                />
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
                <Button icon={<SearchOutlined />} type="primary" htmlType="submit" loading={loadings}>查询</Button>
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
                <Button icon={<ReloadOutlined />} onClick={() => {
                    form.resetFields();
                }} loading={loadings}>重置</Button>
            </Form.Item>


            <Form.Item style={{ marginBottom: '10px' }}>
                <Button icon={<PlusOutlined />} type="primary" onClick={add}>添加</Button>
            </Form.Item>

        </Form>
    }





    const columns: TableColumnsType = [
        {
            title: '用户名',
            dataIndex: 'userName',
            // width: 100,
        },
        {
            title: '账户类型',
            dataIndex: 'userType',
            // width: 100,
            render: (text) => {
                let color = '';
                let label = '';
                if (text == 'root') {
                    color = 'red';
                    label = '系统内置';
                } else if (text == 'visitor') {
                    color = 'green';
                    label = '活动用户';
                }
                return <Tag color={color}>{label}</Tag>;
            },
        },
        {
            title: '角色',
            dataIndex: 'userRole',
            width: 150,
            render: (text) => {
                let single = roleData.find((i) => i.value == text)
                if (single) {
                    return single.label;
                } else {
                    return '';
                }

            },
        },
        {
            title: '真实姓名',
            dataIndex: 'realName',
            width: 150,
        },
        {
            title: '部门',
            dataIndex: 'department',
            width: 150,
        },
        {
            title: '手机号',
            dataIndex: 'phoneNumber',
            width: 180,
        },
        {
            title: '电子邮箱',
            dataIndex: 'userMail',
            width: 180,
        },
        {
            title: '操作',
            dataIndex: 'operation',
            fixed: 'right',
            render: (_: any, record) => {
                return <>
                    <Typography.Link onClick={() => edit(record)} style={{ marginRight: 16 }}>
                        编辑
                    </Typography.Link>

                    <Popconfirm
                        title="确定要删除此账号？"
                        okText="确认"
                        cancelText="取消"
                        onConfirm={() => handleDelete(record)}

                    >
                        <Typography.Link style={{ color: 'red', marginRight: 16 }}>删除</Typography.Link>
                    </Popconfirm>

                    <Popconfirm
                        title="确定要重置此账号？"
                        okText="确认"
                        cancelText="取消"
                        onConfirm={() => reset(record)}
                    >
                        <Typography.Link style={{ color: 'orange' }}>重置</Typography.Link>
                    </Popconfirm>
                </>

            },
        },


    ];
    const [visible, setVisible] = useState<boolean>(false);
    const [modalType, setModalType] = useState<'add' | 'edit'>('add');
    const [editRecord, setEditRecord] = useState<any>(null);
    const [id, setId] = useState<number | undefined>(undefined); //编辑id
    const add = () => {
        setModalType('add')
        setVisible(true)
    }
    const edit = (record: any) => {
        setId(record.id)
        setModalType('edit')
        setVisible(true)
        getUserById({ id: record.id }).then((res: any) => {
            if (res.success) {
                setEditRecord(res.data)
            } else {
                $message.error(res.message);
            }
        })
    }
    const handleDelete = (record: any) => {
        deleteUser({ id: record.id }).then((res: any) => {
            if (res.success) {
                $message.success('删除成功');
                getData()
            } else {
                $message.error(res.message);
            }
        })
    }
    const reset = (record: any) => {
        resetPassword({ userName: record.userName }).then((res: any) => {
            if (res.success) {
                message.success(res.message)
                getData()
            } else {
                message.error(res.message)
            }
        })
    }
    const cancel = () => {
        setVisible(false)
    }
    const submit = (obj: any) => {
        if (modalType == 'add') {
            addUser(obj).then((res: any) => {
                if (res.success) {
                    $message.success('添加成功');
                    setVisible(false)
                    getData()
                } else {
                    $message.error(res.message);
                }
            })
        } else {
            obj['id'] = id
            editUser(obj).then((res: any) => {
                if (res.success) {
                    $message.success('编辑成功');
                    setVisible(false)
                    getData()
                } else {
                    $message.error(res.message);
                }
            })
        }


    }



    const getTable = () => {
        return <Table
            columns={columns}
            dataSource={tableData}
            scroll={{ x: 'max-content' }}
            pagination={false}
            sticky={true}
            style={{ height: '90%', overflowY: 'auto', overflowX: 'hidden' }}
        />
    }





    const total = useRef(0);
    const pageNumRef = useRef(1);
    const pageSizeRef = useRef(10);
    const [current, setCurrent] = useState<number>(1);
    const onChange: PaginationProps['onChange'] = (page, pageSize) => {
        pageNumRef.current = page;
        pageSizeRef.current = pageSize;
        setCurrent(page)
        getData()
    }
    const getPagination = () => {
        return <> <Pagination
            size="small"
            total={total.current}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `共 ${total} 条`}
            onChange={onChange}
            current={current}
        />
            <AddCount visible={visible} cancel={cancel}
                submit={submit} type={modalType}
                initialValues={editRecord}></AddCount>
        </>

    }


    return <>
        <Common top={getTop()} table={getTable()} paginations={getPagination()} />
    </>
}

export default Account